package com.sskj.hangqing.presenter;

import com.google.gson.Gson;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.util.DisposUtil;
import com.sskj.hangqing.bean.PushTradeBean;
import com.sskj.hangqing.bean.TradeBean;
import com.sskj.hangqing.ui.fragment.TradeFragment;
import com.sskj.lib.bean.PageBean;
import com.sskj.lib.http.CallBackOption;
import com.sskj.lib.util.CommonUtil;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;


public class TradeFragmentPresenter extends BasePresenter<TradeFragment> {

    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;

    public void getData(String code) {
        httpService.getAllTrade(code)
                .execute(new CallBackOption<HttpData<PageBean<TradeBean>>>() {
                }.unLoadBind(mView)
                        .execute(httpData -> {
                            if (httpData.getData() == null) {
                                mView.updateUI(new ArrayList<>());
                            } else {
                                mView.updateUI(httpData.getData().getList());
                            }
                        }));
    }

    public void initSocket(String code,boolean isBibi) {
        if (code == null)
            return;
        code = CommonUtil.dealReuqestCode(code);
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinTrade(code,isBibi);
            stockDisposable = stockSocket
                    .map(s -> new Gson().fromJson(s, PushTradeBean.class))
                    .subscribe(data -> mView.updateData(data), e -> {
                    });

        } else {
            if (isBibi) {
                stockSocket.send("{\"type\":\"trader_info\",\"list\":[\"" + code + "\"]}");
            }else {
                stockSocket.send("{\"type\":\"trader_info_lever\",\"list\":[\"" + code + "\"]}");

            }
        }

    }


    @Override
    public void detachView() {
        closeWebSocket();
        super.detachView();
    }

    public void closeWebSocket() {
        if (stockSocket!=null) {
            stockSocket.close();
            stockSocket = null;
        }
        DisposUtil.close(stockDisposable);
    }

}
